package com.lzx.mall_tiny01.controller;

import com.lzx.mall_tiny01.common.api.ResponseVo;
import com.lzx.mall_tiny01.mbg.model.PmsBrand;
import com.lzx.mall_tiny01.service.PmsBrandService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Author: lzx
 * @Date: 2021/4/26 11:02
 */

@Api(tags = "PmsBrandController", description = "商品品牌管理")
@RestController
@RequestMapping("/brand")
public class PmsBrandController {
    @Autowired
    private PmsBrandService brandService;

    private static final Logger LOGGER = LoggerFactory.getLogger(PmsBrandController.class);

    private static <E> ResponseVo isSuccess(int count, E t) {
        ResponseVo responseVo;
        if (count == 1) {
            responseVo = ResponseVo.success(t);
            LOGGER.debug("操作成功,数据：{}", t);
        } else {
            responseVo = ResponseVo.failure("创建失败");
            LOGGER.warn("操作失败，数据：{}", t);
        }
        return responseVo;
    }

    @ApiOperation("获取所有品牌列表")
    @GetMapping("listAll")
    @PreAuthorize("hasAuthority('pms:brand:read')")
    public ResponseVo<List<PmsBrand>> getBrandList() {
        return ResponseVo.success(brandService.listAllBrand());
    }

    @ApiOperation("创建品牌")
    @PostMapping("create")
    @PreAuthorize("hasAuthority('pms:brand:create')")
    public ResponseVo createBrand(@RequestBody PmsBrand brand) {
        int count = brandService.createBrand(brand);
        return isSuccess(count, brand);
    }

    @ApiOperation("删除指定品牌")
    @PostMapping("/delete/{id}")
    @PreAuthorize("hasAuthority('pms:brand:delete')")
    public ResponseVo deleteBrand(@PathVariable("id") Long id) {
        int count = brandService.deleteBrand(id);
        return isSuccess(count, id);
    }
    @PostMapping("update/{id}")
    @ApiOperation("更新指定品牌的信息")
    @PreAuthorize("hasAuthority('pms:brand:update')")
    public ResponseVo updateBrand(@PathVariable("id") Long id, @RequestBody PmsBrand brandDto) {
        int count = brandService.updateBrand(id, brandDto);
        return isSuccess(count, brandDto);
    }

}
